<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.ticket_delete"
          @click="handleDelete">删 除
        </el-button>
      </template>

      <template #menu="{ size, row }">
        <el-button @click="openTicketPackageDialog(row)" text type="text" :size="size">
          票档管理
        </el-button>
      </template>

    </avue-crud>

    <el-dialog title="票档管理" :visible.sync="dialogVisible" width="70%" append-to-body>
      <div class="ticket-package-container">
        <div class="operation-bar">
          <el-button type="primary" size="small" @click="addPackage">添加票档</el-button>
        </div>

        <el-table :data="packageData" border style="width: 100%" v-loading="packageLoading">
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="price" label="价格"></el-table-column>
          <el-table-column prop="details" label="详情"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="editPackage(scope.row)">编辑</el-button>
              <el-button size="mini" type="text" @click="toggleStatus(scope.row)">
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="mini" type="text" style="color: #F56C6C" @click="deletePackage(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog :title="packageForm.id ? '编辑票档' : '添加票档'" :visible.sync="packageFormVisible" width="70%"
        append-to-body>
        <el-form :model="packageForm" ref="packageForm" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="packageForm.name" placeholder="请输入票档名称"></el-input>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number v-model="packageForm.price" :max="9999" :precision="2" :step="1"
              :min="0.01"></el-input-number>
          </el-form-item>
          <el-form-item label="总库存" prop="inventory">
            <el-input-number v-model="packageForm.inventory" :max="99999" step-strictly :step="1"
              :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="详情" prop="details">
            <el-input v-model="packageForm.details" type="textarea" :rows="3" placeholder="请输入票档详情"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="packageForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="packageFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPackageForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/lanqiu/ticket";
import option from "@/const/lanqiu/ticket";
import { mapGetters } from "vuex";
import { getList as getPackageList, add as addPackage, update as updatePackage, remove as removePackage } from "@/api/lanqiu/ticketPackage";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],
      currentRow: {},
      dialogVisible: false,
      // 票档相关数据
      packageData: [],
      packageLoading: false,
      packageFormVisible: false,
      packageForm: {
        name: '',
        price: 0,
        details: '',
        status: 1,
        ticketId: '',
        inventory: 99999
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.ticket_add, false),
        viewBtn: this.vaildData(this.permission.ticket_view, false),
        delBtn: this.vaildData(this.permission.ticket_delete, false),
        editBtn: this.vaildData(this.permission.ticket_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    openTicketPackageDialog(row) {
      this.dialogVisible = true;
      this.currentRow = row;
      this.loadPackageData();
    },
    // 加载票档数据
    loadPackageData() {
      this.packageLoading = true;
      getPackageList(1, 100, { ticketId: this.currentRow.id }).then(res => {
        const data = res.data.data;
        this.packageData = data.records || [];
        this.packageLoading = false;
      }).catch(() => {
        this.packageLoading = false;
      });
    },
    // 添加票档
    addPackage() {
      this.packageForm = {
        name: '',
        price: 0,
        details: '',
        status: 1,
        inventory: 99999,
        ticketId: this.currentRow.id
      };
      this.packageFormVisible = true;
    },
    // 编辑票档
    editPackage(row) {
      this.packageForm = JSON.parse(JSON.stringify(row));
      this.packageFormVisible = true;
    },
    // 切换状态
    toggleStatus(row) {
      const newStatus = row.status === 1 ? 0 : 1;
      const statusText = newStatus === 1 ? '启用' : '禁用';

      this.$confirm(`确定要${statusText}该票档吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const updatedRow = { ...row, status: newStatus };
        updatePackage(updatedRow).then(() => {
          this.$message({
            type: 'success',
            message: `${statusText}成功!`
          });
          this.loadPackageData();
        });
      }).catch(() => { });
    },
    // 删除票档
    deletePackage(row) {
      this.$confirm('确定要删除该票档吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removePackage(row.id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.loadPackageData();
        });
      }).catch(() => { });
    },
    // 提交票档表单
    submitPackageForm() {
      const isNew = !this.packageForm.id;
      const apiFunc = isNew ? addPackage : updatePackage;

      apiFunc(this.packageForm).then(() => {
        this.$message({
          type: 'success',
          message: `${isNew ? '添加' : '编辑'}成功!`
        });
        this.packageFormVisible = false;
        this.loadPackageData();
      }).catch(() => { });
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.ticket-package-container {
  padding: 20px 0;
}

.operation-bar {
  margin-bottom: 20px;
}
</style>
